package cn.org.donald.framework.util;

import cn.org.donald.framework.constant.HttpMethodConstant;
import cn.org.donald.framework.constant.HttpStatus;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import java.io.OutputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * do http request
 *
 * @author : Donald
 * @since : 2021/1/23 8:53
 */
public class HttpsUtil {

    public static JSONObject post(String url, String json) {
        byte[] param = new byte[0];
        if (json != null) {
            param = json.getBytes(StandardCharsets.UTF_8);
        }
        HttpsURLConnection conn = null;
        OutputStream out;
        String result = null;
        try {
            URL url1 = new URL(url);
            conn = (HttpsURLConnection) url1.openConnection();
            // 忽略证书认证
            conn.setHostnameVerifier(new TrustAnyHostNameVerifier());
            conn.setRequestMethod(HttpMethodConstant.POST);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setRequestProperty("Host", url1.getHost());
            conn.setRequestProperty("Content-Type", "application/json");
            out = conn.getOutputStream();
            out.write(param);
            out.close();
            result = StringUtil.inputStreamToString(
                    HttpStatus.OK == conn.getResponseCode()
                            ? conn.getInputStream()
                            : conn.getErrorStream(), StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
        return JSON.parseObject(result);
    }

}

/**
 * ignore all certificate verification
 */
class TrustAnyHostNameVerifier implements HostnameVerifier {
    @Override
    public boolean verify(String s, SSLSession sslSession) {
        return true;
    }
}
